package k2_oop.p9_collection.demo15;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Student {

    private String name;
    private int age;
    private double score;
    private String classNum;
    private static int stuCount = 0;
    private static int ageCount = 0;

    private static Map<String, ArrayList<Double>> classScoreMap = new HashMap<>();

    public Student(String name, int age, double score, String classNum) {
        this.name = name;
        this.age = age;
        this.score = score;
        this.classNum = classNum;
        stuCount++;
        ageCount+=this.age;

        //如果Map中存在以当前班号为key的键值对，把原有的成绩列表取出，并添加当前学生的成绩
        if(classScoreMap.containsKey(classNum)){
            ArrayList<Double> scoreList = classScoreMap.get(classNum);
            scoreList.add(score);
            classScoreMap.put(classNum,scoreList);
        }else{
            ArrayList<Double> scoreList = new ArrayList<>();
            scoreList.add(score);
            classScoreMap.put(classNum,scoreList);
        }

    }

    /**
     * 获取所有学生的平均年龄
     * @return
     */
    public static double getAvgAge(){
        return ageCount/1.0/stuCount;
    }

    /**
     * 按班号计算每个班级的平均成绩
     * @return
     */
    public static String getAvgScoreByClassNum(){

        //获取每个班级的班号和成绩的键值对 的集合
        Set<Map.Entry<String,ArrayList<Double>>> classScore = classScoreMap.entrySet();

        StringBuilder sb = new StringBuilder();
        ArrayList<Double> scoresByClass;
        //第一层遍历，表示遍历每个班级的情况
        for (Map.Entry<String, ArrayList<Double>> stringArrayListEntry : classScore) {
            int scoreSum = 0;
            sb.append(stringArrayListEntry.getKey()+":");
            //获取当前班级的所有学生成绩的集合
            scoresByClass = stringArrayListEntry.getValue();
            //遍历这个班级的所有成绩，求和
            for (Double score : scoresByClass) {
                scoreSum+=score;
            }
            //平均成绩=总成绩/这个班级的学生总数量
            sb.append(scoreSum/scoresByClass.size()+" ");
        }

        return sb.toString();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    public String getClassNum() {
        return classNum;
    }

    public void setClassNum(String classNum) {
        this.classNum = classNum;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                ", classNum='" + classNum + '\'' +
                '}';
    }
}
